import { createRouter, createWebHashHistory } from 'vue-router'
import LiveView from '../views/LiveView.vue'
import Login from '../views/Login.vue'

const routes = [
  {
    path: '/',
    redirect: '/login'  // 重定向到登录页面
  },
  {
    path: '/login',
    name: 'login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/live',
    name: 'live',
    component: LiveView,
    meta: { requiresAuth: true }
  },
  {
    path: '/config',
    name: 'config',
    component: () => import('../views/ConfigView.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: 'camera/video',
        name: 'video',
        component: () => import('../components/camera/VideoConfig.vue')
      },
      {
        path: 'camera/image',
        name: 'image',
        component: () => import('../components/camera/ImageConfig.vue')
      },
      {
        path: 'camera/osd',
        name: 'osd',
        component: () => import('../components/camera/OSDConfig.vue')
      },
      {
        path: 'network/basic',
        name: 'basic',
        component: () => import('../components/network/BasicConfig.vue')
      },
      {
        path: 'system/upgrade',
        name: 'upgrade',
        component: () => import('../components/system/UpgradeConfig.vue')
      },
      {
        path: 'system/user',
        name: 'user',
        component: () => import('../components/system/UserManage.vue')
      }
    ]
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 检查路由是否需要认证
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth !== false);
  
  // 获取认证状态
  const isAuthenticated = localStorage.getItem('access_token');
  const tokenExpires = localStorage.getItem('token_expires');
  const isTokenExpired = tokenExpires && parseInt(tokenExpires) < Date.now();
  
  // 如果token过期，清除认证信息
  if (isTokenExpired) {
    localStorage.removeItem('access_token');
    localStorage.removeItem('refresh_token');
    localStorage.removeItem('token_expires');
    localStorage.removeItem('user_info');
  }
  
  if (requiresAuth && (!isAuthenticated || isTokenExpired)) {
    // 需要认证但未登录或token过期，重定向到登录页面
    next('/login');
  } else if (to.path === '/login' && isAuthenticated && !isTokenExpired) {
    // 已登录且token未过期的用户访问登录页面，重定向到首页
    next('/live');
  } else {
    // 其他情况正常导航
    next();
  }
})

export default router